<template>
  <el-dialog :title="title" :visible.sync="visible" width="500px" append-to-body>
    <p>{{ user.name }}</p>
    <el-select v-model="selectedList" multiple placeholder="请选择">
      <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
    </el-select>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm"> 保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { queryByUserId, saveUserRole } from '@/api/mange/userRole'
import { queryRoleList } from '@/api/mange/role'

export default {
  name: 'userRoleModal',
  data() {
    return {
      title: '配置角色',
      visible: false,
      buttonLoading: false,
      user: {},
      form: {},
      roleList: [],
      selectedList: []
    }
  },

  methods: {
    init(user) {
      this.selectedList = []
      console.log(user)
      this.user = user
      this.getRoleList()
      this.queryUserRoles()
      this.visible = true
    },
    getRoleList() {
      queryRoleList().then((res) => {
        this.roleList = res.data.records
      })
    },
    queryUserRoles() {
      queryByUserId(this.user.id).then((res) => {
        if (res.data.roles.length > 0) {
          this.selectedList = res.data.roles.map((r) => {
            return r.id
          })
        } else {
          this.selectedList = []
        }
      })
    },
    submitForm() {
      console.log(this.selectedList)
      let roles = this.selectedList.map((s) => {
        return { id: s }
      })

      let data = {
        userId: this.user.id,
        roles: roles
      }
      saveUserRole(data)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('保存成功')
          } else {
            this.$message.error(res.msg || '保存失败')
          }
          this.$emit('ok')
        })
        .finally((res) => {
          this.buttonLoading = false
          this.visible = false
        })
    },
    cancel() {
      this.visible = false
    }
  }
}
</script>

<style scoped></style>
